<template>
  <van-address-edit
    :area-list="areaList"
    show-delete
    show-set-default
    show-search-result
    :search-result="searchResult"
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    delete-button-text="清空"
    @save="onSave"
    @delete="onDelete"
    @change-detail="onChangeDetail"
    :address-info="addressInfo"
  />
</template>

<script setup>
import { ref, onMounted } from "vue";
import { showToast } from "vant";

import { areaList } from "@vant/area-data";

import { useAddrStore } from "@/stores/addr.js";

const addrS = useAddrStore();

const searchResult = ref([]);

let addressInfo = ref();

onMounted(() => {
  addressInfo.value = addrS.defaultAddr;
});

// 判断有没有 isDefault 字段
function onSave(data) {
  // 有就先删除原始的默认值
  if (data.isDefault === true) {
    addrS.addrList.forEach((item) => {
      item.isDefault = false;
    });

    addrS.addrList[Number(data.id - 1)] = {
      name: data.name,
      tel: data.tel,
      isDefault: data.isDefault,
      areaCode: data.areaCode,
      addressDetail: data.addressDetail,
      address: data.province + data.city + data.county + data.addressDetail,
    };
  } else {
    // 没有就直接添加
    addrS.addrList[Number(data.id - 1)] = {
      name: data.name,
      tel: data.tel,
      address: data.province + data.city + data.county + data.addressDetail,
      isDefault: data.isDefault,
      areaCode: data.areaCode,
      addressDetail: data.addressDetail,
    };
  }
  showToast("修改成功");
}
function onDelete() {
  addressInfo.value = {};
  showToast("清空成功");
}
function onChangeDetail(val) {
  if (val) {
    searchResult.value = [
      {
        name: "物资大厦",
        address: "延安东路",
      },
    ];
  } else {
    searchResult.value = [];
  }
}
</script>

<style lang="less" scoped>
h2 {
  line-height: 1;
  font-size: 4.533vw;
  font-weight: 600;
  margin-bottom: 2.133vw;
  margin-left: 5.067vw;
}
:deep(.van-button--round) {
  border-radius: 2vw;
}
:deep(.van-button--primary) {
  background-color: rgb(255, 60, 80);
  border: none;
}
:deep(.van-button--default) {
  background-color: rgb(153, 153, 153);
  border: none;
  color: #fff;
  margin-top: 6vw;
}
:deep(.van-address-edit__buttons) {
  margin-top: 31vw;
}

:deep(.van-switch--on) {
  background-color: rgb(255, 60, 80);
}
</style>
